<template>
  <div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable :columns="columns" :dataSource="userDataSource" :row-key="(row) => row.id" ref="actionRef"
                  :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" :pagination="false">
        <template #tableTitle>
          <n-button type="primary" @click="handlerAddAdminUser">
            <template #icon>
              <n-icon>
                <PlusOutlined/>
              </n-icon>
            </template>
            添加用户
          </n-button>
        </template>
        <template #toolbar>
          <n-button type="error" @click="batchDelete">批量删除</n-button>
        </template>
        <template #action>
          <TableAction/>
        </template>
      </BasicTable>
    </n-card>

    <basicModal @register="modalRegister" ref="modalRef" class="basicModal" @on-ok="okModal">
      <template #default>
        <BasicForm v-if="isEdit" @register="editRegister" class="basicForm">
          <template #roleSlot="{ model, field }">
            <n-select v-model:value="model[field]" clearable :options="selectOptions" @update:value="changeRoleType"/>
          </template>
          <template #chanSlot="{ model, field }">
            <n-select v-model:value="model[field]" clearable multiple :disabled="!isStaff" :options="chanlOptions"/>
          </template>
        </BasicForm>
        <BasicForm v-else @register="addRegister" class="basicForm">
          <template #roleSlot="{ model, field }">
            <n-select v-model:value="model[field]" clearable :options="selectOptions" @update:value="changeRoleType"/>
          </template>
          <template #chanSlot="{ model, field }">
            <n-select v-model:value="model[field]" clearable :disabled="!isStaff" multiple :options="chanlOptions"/>
          </template>
        </BasicForm>
      </template>
    </basicModal>

    <n-modal v-model:show="showModalTree" :show-icon="false" preset="dialog" :title="editRoleTitle">
      <div class="py-3 menu-list">
        <n-tree
          block-line
          checkable
          :virtual-scroll="true"
          :data="treeDataSource"
          :expandedKeys="expandedKeys"
          :checked-keys="checkedKeys"
          style="max-height: 950px; overflow: hidden"
          @update:checked-keys="checkedTree"
          @update:expanded-keys="onExpandedKeys"/>
      </div>
      <template #action>
        <n-space>
          <n-button type="info" ghost icon-placement="left" @click="packHandle">
            全部{{ expandedKeys.length ? '收起' : '展开' }}
          </n-button>

          <n-button type="info" ghost icon-placement="left" @click="checkedAllHandle">
            全部{{ checkedAll ? '取消' : '选择' }}
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import {h, onMounted, reactive, ref, unref, toRefs, watch} from 'vue';
  import {useDialog, useMessage} from 'naive-ui';
  import {BasicTable, TableAction} from '@/components/Table';
  import {addCloumns, columns, editCloumns, setIsStaff} from './columns';
  import {useRouter} from 'vue-router';
  import {useModal} from '@/components/Modal/index';
  import {DeleteOutlined, EditOutlined, PlusOutlined, QuestionCircleOutlined} from '@vicons/antd';
  import {BasicForm, useForm} from '@/components/Form/index';
  import {
    addAdminUser,
    AddAdminUserParams, changePassword,
    deleteAdminUser,
    getSystemUserList,
    updateSystemUser
  } from "@/api/system/user";
  import {getMenuList} from "@/api/system/menu";
  import {getChanList} from "@/api/game/chan";

  const router = useRouter();
  const message = useMessage();
  const dialog = useDialog();
  const actionRef = ref();

  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const editRoleTitle = ref('');
  const checkedKeys = ref([]);
  const checkedRowKes = ref([]);
  const userDataSource = ref([]);
  const expandedKeys = ref([]);
  const updateAdmin = ref({});
  const checkedAll = ref(false);
  const isStaff = ref(false);
  const selectOptions = ref([
    {
      value: "admin",
      label: "系统管理员"
    }, {
      value: "super",
      label: "超级系统管理员"
    }, {
      value: "staff",
      label: "运维人员"
    }
    , {
      value: "customer",
      label: "客服"
    }
  ]);
  const chanlOptions = ref([]);
  const menuNodeKeys = ref([]);
  const isEdit = ref(false);
  const showModalTree = ref(false);
  const updateUser = ref({});
  const treeDataSource = ref([]);

  const actionColumn = reactive({
    width: 400,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record: any) {
      return h(TableAction, {
        style: 'button',
        actions: [
          {
            label: '权限配置',
            type: 'warning',
            onClick: handleAuth.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
          {
            label: '重置密码',
            type: 'success',
            icon: EditOutlined,
            onClick: handleResetPassword.bind(null, record),
            ifShow: () => {
              return true;
            },
            // auth: ['basic_list'],
          },
          {
            label: '编辑',
            type: 'info',
            icon: EditOutlined,
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
            // auth: ['basic_list'],
          },
          {
            label: '删除',
            type: 'error',
            icon: DeleteOutlined,
            onClick: handleDelete.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
        ],
      });
    },
  });

  const [modalRegister, {openModal, closeModal, setSubLoading, setProps}] = useModal({
    title: '编辑',
    width: 600
  });
  const [addRegister, {submit: addSubmit, setFieldsValue: addSetFieldsValue}] = useForm({
    gridProps: {cols: 1},
    collapsedRows: 3,
    labelWidth: 120,
    layout: 'horizontal',
    submitButtonText: '提交保存',
    showActionButtonGroup: false,
    schemas: addCloumns
  });

  const [editRegister, {submit: editSubmit, setFieldsValue: editSetFieldsValue}] = useForm({
    gridProps: {cols: 1},
    collapsedRows: 3,
    labelWidth: 120,
    layout: 'horizontal',
    submitButtonText: '提交保存',
    showActionButtonGroup: false,
    schemas: editCloumns
  });

  //监听值变化
  watch(isStaff, (value) => {
    setIsStaff(value)
  });


  //提交数据
  async function okModal() {

    if (unref(isEdit)) {
      await submitEdit();
    } else {
      await submitAdd()
    }
  }

  async function submitEdit() {
    let formRes = {};
    try {
      formRes = await editSubmit();
      let tmp = unref(updateAdmin);
      let params: any = Object.assign(tmp, formRes);
      params.status = params.status ? "able" : "disable";
      const adminParam = (params as any) as AddAdminUserParams;
      if (unref(isStaff)) {
        if (adminParam.chanList == "") {
          message.success('运维用户必须选择通道');
          return
        } else {
          if (params.chanList && params.chanList.length > 0) {
            adminParam.chanList = params.chanList.join(",")
          }
        }
      } else {
        adminParam.chanList = ""
      }
      await updateSystemUser(adminParam);
      closeModal();
      reloadTable();
      message.success('编辑成功');
    } catch (e) {
      if (!formRes) {
        message.error('验证失败，请填写完整信息');
      }
    } finally {
      setSubLoading(false);
    }
  }


  async function confirmForm(e: any) {
    e.preventDefault();
    try {
      formBtnLoading.value = true;
      let firstPsids = [];
      let thirdPsids = [];
      let secPsids = [];
      for (let key of  unref(checkedKeys)) {
        if (key.indexOf("_") > 0) {
          let ids = key.split("_");
          if (ids.length == 2) {
            secPsids.push(ids[1])
          } else if (ids.length == 3) {
            thirdPsids.push(ids[2])
          }
        } else {
          firstPsids.push(key)
        }
      }
      let params = {
        ...unref(updateUser),
        firstPsIds: (firstPsids.length > 0) ? firstPsids.join(",") : '',
        secondPsIds: (secPsids.length > 0) ? secPsids.join(",") : '',
        thirdPsIds: (thirdPsids.length > 0) ? thirdPsids.join(",") : ''
      };
      await updateSystemUser(params);
      message.success('修改成功,下次登录生效');
      setTimeout(() => {
        showModalTree.value = false;
        reloadTable();
      });
    } finally {
      formBtnLoading.value = false;
    }
  }

  async function submitAdd() {
    let formRes = {};
    try {
      formRes = await addSubmit()
    } catch (e) {
      message.error('验证失败，请填写完整信息');
      setSubLoading(false);
    }
    try {
    let params: any = Object.assign({}, formRes);
    delete params.repassword;
    params.status = params.status ? "able" : "disable";
    params.chanList = unref(params.chanList) ? unref(params.chanList).join(",") : "";
    params = Object.assign({}, {
      firstPsIds: '',
      secondPsIds: '',
      id: 0,
      createTime: '',
      updateTime: '',
      thirdPsIds: '',
      iconUrl: '',
      email: '',
      desc: ''
    }, params);
    const adminParam = (params as any) as AddAdminUserParams;
      await addAdminUser(adminParam);
    } finally {
      setSubLoading(false);
    }
    closeModal();
    reloadTable();
    message.success('添加成功');
  }

  async function handleResetPassword(record: any) {
    console.log(record);
    dialog.info({
      title: '提示',
      content: `您想重置密码吗？`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        await changePassword({
          userId: unref(record).id,
          newPsw: "123456",
        });
        message.success('重置成功');
      },
      onNegativeClick: () => {
      },
    });
  }

  async function handleAuth(record: any) {
    editRoleTitle.value = `分配 ${record.username} 的权限`;

    let firstPsids = record.firstPsIds.split(",");

    let secPsIds = record.secondPsIds.split(",");

    let thiPsIds = record.thirdPsIds.split(",");

    let menuKeys = unref(menuNodeKeys);

    checkedKeys.value = [];

    function handKeys(key: string) {
      if (!checkedKeys.value.includes(key)) {
        if (key && key != '') {
          checkedKeys.value.push(key)
        }
      }
      if (key.indexOf("_") > 0) {
        handKeys(key.substring(0, key.lastIndexOf("_")))
      }
    }

    for (let psIds of  thiPsIds) {
      for (let key of menuKeys) {
        if (key.indexOf(psIds) > 0 && key.split("_").length == 3) {
          handKeys(key);
        }
      }
    }

    for (let psIds of  secPsIds) {
      for (let key of menuKeys) {
        if (key.indexOf(psIds) > 0 && key.split("_").length == 2) {
          handKeys(key)
        }
      }
    }
    for (let psIds of  firstPsids) {
      handKeys(psIds)
    }

    updateUser.value = record;
    showModalTree.value = true;
  }

  function changeRoleType(value) {
    isStaff.value = false;
    if (value === "staff") {
      isStaff.value = true
    }
  }

  function onCheckedRow(rowKeys: any[]) {
    checkedRowKes.value = rowKeys;
  }

  function checkedTree(keys) {
    checkedKeys.value = [...keys];
  }

  function onExpandedKeys(keys) {
    expandedKeys.value = keys;
  }

  function checkedAllHandle() {
    if (!checkedAll.value) {
      checkedKeys.value = menuNodeKeys.value;
      checkedAll.value = true;
    } else {
      checkedKeys.value = [];
      checkedAll.value = false;
    }
  }

  function packHandle() {
    if (expandedKeys.value.length) {
      expandedKeys.value = [];
    } else {
      expandedKeys.value = treeDataSource.value.map((item: any) => item.key) as [];
    }
  }

  function reloadTable() {
    loadUserDataSource();
    actionRef.value.reload();
  }


  async function handlerAddAdminUser() {
    isEdit.value = false;
    setProps({
      title: '添加系统管理员',
    });
    await openModal();
  }

  async function handleEdit(record: any) {
    isEdit.value = true;
    updateAdmin.value = unref(record);
    setProps({
      title: '编辑'
    });
    await openModal();
    const fileds: any = Object.assign({}, unref(record));
    fileds.status = record.status == 'able';
    isStaff.value = false;
    if (fileds.roleType === "staff") {
      isStaff.value = true
    }
    if (fileds.chanList && fileds.chanList != '') {
      fileds.chanList = fileds.chanList.split(",")
    }
    editSetFieldsValue(fileds)
    // router.push({ name: 'basic-info', params: { id: record.id } });
  }

  function handleDelete(record: Recordable) {
    dialog.info({
      title: '提示',
      content: `您想删除${record.username}吗`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        await deleteAdminUser(record);
        message.success('删除成功');
        reloadTable()
      },
      onNegativeClick: () => {
      },
    });
  }

  //批量删除
  function batchDelete() {
    const userids = unref(checkedRowKes);
    if (userids.length === 0) {
      message.warning("至少选择一条数据");
      return;
    }
    dialog.info({
      title: '提示',
      content: `您想删除选中管理员用户吗`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        await deleteAdminUser({idArrs: userids});
        message.success('删除成功');
        reloadTable()
      },
      onNegativeClick: () => {
      },
    });

  }

  // 加载用户数据
  async function loadUserDataSource() {
    const dataSource = await getSystemUserList();
    userDataSource.value = dataSource;
  }


  onMounted(async () => {
    //加载用户数据
    await loadUserDataSource();
    // 加载权限树
    await loadTreeValues();
    //加载通道选项
    await loadChanOptions();
  });

  async function loadChanOptions() {
    let chanAll = await getChanList({
      page:0,
      pageSize: 10,
      chanName: ''
    });
    chanlOptions.value = chanAll.list.map((item: any) => {
      return {value: item.chanId, label: item.chanName}
    })
  }


  async function loadTreeValues() {
    let menuList = await getMenuList();

    function handlerMenuTree(menuList: any, parentKey: string) {
      for (let item: any of menuList) {
        if (item.menuArrs && item.menuArrs.length > 0) {
          item.children = item.menuArrs;
          handlerMenuTree(item.menuArrs, (parentKey ? (parentKey + "_") : parentKey) + item.psId)
        }
        item.label = item.psName;
        item.key = (parentKey ? (parentKey + "_") : parentKey) + item.psId;
        unref(menuNodeKeys).push(item.key)
      }
    }

    handlerMenuTree(menuList, "");
    treeDataSource.value = menuList as any[];
  }

</script>

<style lang="less" scoped>
</style>
